package org.ala.tiktools.sharddb.mybatis.router;

/**
 * 库表信息
 *
 * @author ala
 * @date 2025-02-20 14:48
 */
public class ShardInfo {

    protected String shardDB;
    protected String shardTable;
    /**
     *  相对于本次操作的第几个分库分表
     *  <p> 相同的 shardDB 和 shardTable 允许被选择多次
     *  <p> 在hashCode中占6位，所以同一个分库分表只允许重复64次
     */
    protected int idx = 0;

    public static ShardInfo build(String db, String table) {
        ShardInfo info = new ShardInfo();
        info.shardDB = db;
        info.shardTable = table;
        info.idx = 0;
        return info;
    }

    /**
     *  空分库分表
     */
    public static ShardInfo EMPTY = ShardInfo.build("TOTAL", "TOTAL");

    /**
     *  db 和 table 的hashCode各站13位，idx占6位
     */
    @Override
    public int hashCode() {
        int db = this.shardDB.hashCode(), table = this.shardTable.hashCode();
        return db + table + idx;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof ShardInfo)) {return false;}
        ShardInfo si = (ShardInfo) obj;
        return this.shardDB.equals(si.shardDB) && this.shardTable.equals(si.shardTable) && this.idx == si.idx;
    }

    @Override
    public String toString() {
        return String.format("[%s:%s:%d]", this.shardDB, this.shardTable, this.idx);
    }

    public String getShardDB() {
        return shardDB;
    }

    public void setShardDB(String shardDB) {
        this.shardDB = shardDB;
    }

    public ShardInfo shardDB(String shardDB) {
        setShardDB(shardDB);
        return this;
    }

    public String getShardTable() {
        return shardTable;
    }

    public void setShardTable(String shardTable) {
        this.shardTable = shardTable;
    }

    public ShardInfo shardTable(String shardTable) {
        setShardTable(shardTable);
        return this;
    }

    public int getIdx() {
        return idx;
    }

    public void setIdx(int idx) {
        this.idx = idx;
    }

    public ShardInfo idx(int idx) {
        setIdx(idx);
        return this;
    }
}
